package com.sykj.cloud.auth.controller;


import com.sykj.cloud.auth.form.LoginBody;

import com.sykj.cloud.auth.service.SysUserLoginService;
import com.sykj.cloud.common.core.domain.R;
import com.sykj.cloud.common.core.utils.StringUtils;
import com.sykj.cloud.common.log.annotation.Log;
import com.sykj.cloud.common.log.enums.LogUserType;
import com.sykj.cloud.common.security.service.TokenService;
import com.sykj.cloud.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * token 控制
 *
 * @author ruoyi
 */
@RestController
public class UserTokenController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysUserLoginService userLoginService;


    @GetMapping("verifyImgCodeCreate")
    public boolean verifyImgCodeCreate() {
        return userLoginService.verifyCreateCapcha();
    }


    @PostMapping("/login")
    @Log(title = "用户登录", logUserType = LogUserType.LOGIN)
    public R<?> login(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser userInfo = userLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @DeleteMapping("logout")
    @Log(title = "用户注销", logUserType = LogUserType.LOG_OUT)
    public R<?> logout(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUsers(request);
        if (StringUtils.isNotNull(loginUser)) {
            String username = loginUser.getLoginName();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUsers(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }
}
